package com.yc.backstage.common.service;

import com.yc.backstage.common.constant.UserConstants;
import com.yc.backstage.entity.LoginUser;
import com.yc.backstage.entity.SysUser;
import com.yc.backstage.entity.vo.RegisterVO;
import com.yc.backstage.service.SysUserService;
import com.yc.backstage.utils.SecurityUtils;
import com.yc.common.expection.ServiceException;
import com.yc.common.expection.UserPasswordNotMatchException;
import com.yc.common.utils.StringUtils;
import com.yc.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Classname AuthorizationServie
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/8/8 10:46
 * @Created by Mikechen
 */
@Component
public class AuthorizationServieImpl {

    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtTokenServiceImpl jwtTokenService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 登录验证
     *
     * @param username
     * @param password
     * @return
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser user = (LoginUser) authentication.getPrincipal();
        // 生成token
        return jwtTokenService.createToken(user);
    }

    /**
     * 注册
     *
     * @param registerVO
     * @return
     */
    public String register(RegisterVO registerVO) {
        String msg = "";
        String username = registerVO.getUsername();
        String password = registerVO.getPassword();
        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(username))) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(registerVO.getPassword()));
            boolean regFlag = sysUserService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                msg = "注册失败,请联系系统管理人员";
            }
        }
        return msg;
    }
}
